﻿using ClosedXML.Excel;
using DocumentFormat.OpenXml.Wordprocessing;
using Microsoft.Extensions.Configuration;
using Serilog;
using Spectre.Console;
using System.ComponentModel;
using System.Diagnostics;
using WorkTool.Helpers;

namespace WorkTool
{
    public class WorkMonthlyReport : ITools
    {
        public void ToolsMethod(IConfigurationRoot config)
        {
            var options = new List<(int Index, string Description)>{
                new (1, "本月"),
                new (2, "上月"),
                new (3, "全部"),
                new (4, "自定义"),
                new (0, "返回上一级")
            };
            DateTime? date = null;
            while (true)
            {
                ToolHelper.ConsoleClear();
                var selection = AnsiConsole.Prompt(
                    new SelectionPrompt<(int Index, string Description)>()
                        .Title("[green1]请选择：[/]")
                        .PageSize(10)
                        .UseConverter(option => $"[yellow]【{option.Description}】[/]")
                        .AddChoices(options));
                switch (selection.Index)
                {
                    case 1:
                        date = DateTime.Now;
                        break;

                    case 2:
                        date = DateTime.Now.Date.AddMonths(-1);
                        break;

                    case 3:
                        date = null;
                        break;

                    case 4:
                        while (true)
                        {
                            var dateReadLine = AnsiConsole.Ask<string>("[bold][green1]请输入要查询的月份（格式：yyyy-MM）：[/] [/]");
                            if (DateTime.TryParse(dateReadLine, out var dt))
                            {
                                date = dt;
                                break;
                            }
                            else
                            {
                                AnsiConsole.MarkupLine("[yellow]格式错误，请重新输入！[/]");
                            }
                        }
                        break;

                    case 0:
                        AnsiConsole.MarkupLine("[green]正在返回上一级...[/]");
                        return;

                    default:
                        break;
                }
                ToolHelper.ConsoleClear();
                AnsiConsole.Markup($"[bold][aqua]当前选择：【{(date.HasValue ? "查询月份：" + date.Value.ToString("yyyy-MM") : "查询全部数据")}】[/][/] ");
                Console.SetCursorPosition(0, 2);
                var worksheetName = "all";
                var worksheet1Name = "next month";
                string? startDate = null;
                string? endDate = null;
                if (date.HasValue)
                {
                    var startMonth = date.Value.AddDays(1 - date.Value.Day);
                    worksheetName = $"{ToolHelper._month[startMonth.ToString("MM")]}.,{startMonth:yyyy}";
                    startDate = startMonth.ToString("yyyy-MM-dd");
                    endDate = startMonth.AddMonths(1).AddDays(-1).ToString("yyyy-MM-dd");
                    var nextMonth = startMonth.AddMonths(1);
                    worksheet1Name = $"Plan_{ToolHelper._month[nextMonth.ToString("MM")]}.,{nextMonth:yyyy}";
                }
                AnsiConsole.Status().Start("数据加载中...", ctx =>
                {
                    ctx.Spinner(Spinner.Known.Star);
                    ctx.SpinnerStyle(Spectre.Console.Style.Parse("green"));
                    var reportList = new List<WorkMonthlyReportResult>();
                    var nextMonthList = new List<WorkMonthlyReportResult>();
                    foreach (var projects in SettingsHelper._workMonthlyReportSettings.Project)
                    {
                        foreach (var item in projects.ProjectGit)
                        {
                            var (IsSuccess, Message) = GitHelper.ExecuteGitCommand("fetch", item.ProjectPath);
                            if (!string.IsNullOrWhiteSpace(Message))
                                Log.Error($"[git fetch]{Message}");
                            ctx.Status($"正在获取项目【{projects.ProjectName} -> {Path.GetFileName(item.ProjectPath.TrimEnd('\\'))}】分支【{item.Branch}】的提交信息...");
                            ctx.Spinner(Spinner.Known.Star);
                            ctx.SpinnerStyle(Spectre.Console.Style.Parse("green"));
                            Thread.Sleep(1000);
                            var (Data, ErrorMessage) = GitHelper.GetGitCommit(item.Branch, SettingsHelper._workMonthlyReportSettings.Author, item.ProjectPath, startDate, endDate);
                            if (!string.IsNullOrWhiteSpace(ErrorMessage))
                            {
                                AnsiConsole.MarkupLine($"[red]获取项目【{projects.ProjectName} -> {Path.GetFileName(item.ProjectPath.TrimEnd('\\'))}】分支【{item.Branch}】的提交信息失败\n\t错误信息：\n\t{ErrorMessage}[/]");
                                continue;
                            }

                            ctx.Status($"正在处理项目【{projects.ProjectName} -> {Path.GetFileName(item.ProjectPath.TrimEnd('\\'))}】分支【{item.Branch}】的数据...");
                            ctx.Spinner(Spinner.Known.Star);
                            ctx.SpinnerStyle(Spectre.Console.Style.Parse("green"));
                            Thread.Sleep(1000);

                            foreach (var data in Data)
                            {
                                if (!reportList.Any(x => x.CompletedJobs.Equals(data.Message)))
                                {
                                    reportList.Add(new WorkMonthlyReportResult
                                    {
                                        BU = SettingsHelper._workMonthlyReportSettings.BU,
                                        EnglishName = SettingsHelper._workMonthlyReportSettings.EnglishName,
                                        ChineseName = SettingsHelper._workMonthlyReportSettings.ChineseName,
                                        StaffCode = SettingsHelper._workMonthlyReportSettings.StaffCode,
                                        ProjectName = projects.ProjectName,
                                        ProjectCode = projects.ProjectCode,
                                        CompletedJobs = data.Message
                                    });
                                }
                            }
                        }
                        nextMonthList.Add(new WorkMonthlyReportResult
                        {
                            BU = SettingsHelper._workMonthlyReportSettings.BU,
                            EnglishName = SettingsHelper._workMonthlyReportSettings.EnglishName,
                            ChineseName = SettingsHelper._workMonthlyReportSettings.ChineseName,
                            StaffCode = SettingsHelper._workMonthlyReportSettings.StaffCode,
                            ProjectName = projects.ProjectName,
                            ProjectCode = projects.ProjectCode
                        });
                    }
                    ctx.Status("生成Excel文件中...");
                    ctx.Spinner(Spinner.Known.Star);
                    ctx.SpinnerStyle(Spectre.Console.Style.Parse("green"));
                    Thread.Sleep(1000);
                    using var workbook = new XLWorkbook(Path.Combine(Directory.GetCurrentDirectory(), "WorkMonthlyReportTemplate.xlsx"));
                    var worksheet = workbook.Worksheet(1);
                    worksheet.Name = worksheetName;
                    worksheet.Cell(3, 1).InsertData(reportList);
                    var worksheet1 = workbook.Worksheet(2);
                    worksheet1.Name = worksheet1Name;
                    worksheet1.Cell(3, 1).InsertData(nextMonthList);
                    var excelPath = Path.Combine(SettingsHelper._fileSettings.SaveFolder, $"Monthly Project Report_{worksheetName}_{SettingsHelper._workMonthlyReportSettings.EnglishName}{(SettingsHelper._fileSettings.SaveFileNameRandom ? $"_{new Random().Next(10000, 99999)}" : "")}.xlsx");
                    workbook.SaveAs(excelPath);
                    AnsiConsole.MarkupLine($"[green1]文件已保存至\n[/] [bold][aqua]{excelPath}[/][/]");
                    Process.Start(new ProcessStartInfo
                    {
                        FileName = excelPath,
                        UseShellExecute = true
                    });
                });
                AnsiConsole.MarkupLine("[grey]按任意键继续...[/]");
                Console.ReadKey();
            }
        }
    }

    public class WorkMonthlyReportResult
    {
        /// <summary>
        /// 部门
        /// </summary>
        [Description("部门")]
        public string BU { get; set; }

        /// <summary>
        /// 英文名
        /// </summary>
        [Description("英文名")]
        public string EnglishName { get; set; }

        /// <summary>
        /// 中文名
        /// </summary>
        [Description("中文名")]
        public string ChineseName { get; set; }

        /// <summary>
        /// 工号
        /// </summary>
        [Description("工号")]
        public string StaffCode { get; set; }

        /// <summary>
        /// 项目名称
        /// </summary>
        [Description("项目名称")]
        public string ProjectName { get; set; }

        /// <summary>
        /// 项目编号
        /// </summary>
        [Description("项目编号")]
        public string ProjectCode { get; set; }

        /// <summary>
        /// 本月完成的工作
        /// </summary>
        [Description("本月完成的工作")]
        public string CompletedJobs { get; set; }
    }
}